package com.yc;

import com.google.gson.internal.bind.util.ISO8601Utils;

import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.BindException;
import java.net.ServerSocket;
import java.net.Socket;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

public class Test4_Server_ReaderWriter {
    public static void main(String[] args) throws IOException {
        final int port =10000;
        ServerSocket ss= null;
        for(int i=10000;i<65535;i++){
            try {
                ss=new ServerSocket(i);
            } catch ( Exception e) {
                e.printStackTrace();
                if (e instanceof BindException) {
                    System.out.println("端口："+i+"已经被占用");
                }
            }
        }
        System.out.println(ss.getInetAddress().getHostName() + "启动了端口号：***" + ss.getLocalPort());
        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date d= null;
        String time = null;

        while(true){
             Socket s =ss.accept();//阻塞式的方法
            System.out.println("获取了一个与客户端："+s.getRemoteSocketAddress());
            d=new Date();
            time= dateFormat.format(d);

            //套接字编程的底层就是io，这是什么流    输入、输出
            //转换流，将字节流转换为字符流
            try (OutputStreamWriter oos =new OutputStreamWriter(s.getOutputStream());){
                oos.write(time );
                oos.flush();
            }catch (Exception e){
                e.printStackTrace();
            }
            s.close();
            System.out.println("服务器断开与客户端的联接");
         }
    }
}
